from multiprocessing import process
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from werkzeug.utils import secure_filename
import os
import sys
import signal
import shutil
import time
from algorithms.VoiceGeneration import voice_generator
from algorithms.Ocr import ocr_engine
from algorithms.TextToImage import image_generator
from algorithms.Translator import translator_engine
from algorithms.VideoEditing import text_to_video, split_video, add_text_to_video, apply_transition
from algorithms.TextGeneration import generate_text_api
from algorithms.EmotionAnalysis import emotion_analyzer
from algorithms.RemoveWatermark import watermark_remover
from algorithms.TextSummary import text_summarizer
from algorithms.MusicGeneration import music_generator

app = Flask(__name__)
CORS(app)

@app.route('/api/voice-generation', methods=['POST'])
def generate_voice():
    """生成语音API"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        text = data.get('text', '').strip()
        language = data.get('language', '')
        rate = data.get('rate', 1.0)
        
        if not text:
            return jsonify({"error": "文本不能为空"}), 400
        
        if not language:
            return jsonify({"error": "请选择语言"}), 400
        
        # 调用语音生成算法
        result = voice_generator.generate_speech(text, language, rate)
        
        if not result['success']:
            return jsonify({"error": result['error']}), 400
        
        audio_path = result['audio_path']
        
        # 发送音频文件
        response = send_file(
            audio_path,
            mimetype='audio/mpeg',
            as_attachment=False,
            download_name=f"voice_{os.path.basename(audio_path)}.mp3"
        )
        
        # 设置清理回调
        @response.call_on_close
        def cleanup():
            voice_generator.cleanup_audio_file(audio_path)
        
        return response
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/text-generation/model-info', methods=['GET'])
def get_text_model_info():
    """获取文本生成模型信息"""
    try:
        from algorithms.TextGeneration import text_generator
        model_info = text_generator.get_model_info()
        return jsonify(model_info)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/text-generation/status', methods=['GET'])
def check_text_generation_status():
    """检查文本生成服务状态"""
    try:
        from algorithms.TextGeneration import text_generator
        status = text_generator.check_api_status()
        return jsonify(status)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/voice-languages', methods=['GET'])
def get_languages():
    """获取支持的语言列表"""
    try:
        languages = voice_generator.get_supported_languages()
        return jsonify({
            "languages": languages,
            "count": len(languages)
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({
        "status": "healthy",
        "service": "voice-generation",
        "version": "1.0.0"
    })

@app.route('/', methods=['GET'])
def index():
    """根路径"""
    return jsonify({
        "message": "语音合成服务已启动",
        "endpoints": {
            "generate_voice": "/api/voice-generation",
            "get_languages": "/api/voice-languages",
            "health_check": "/api/health"
        }
    })

@app.route('/api/ocr-recognition', methods=['POST'])
def ocr_recognition():
    try:
        # 检查是否有文件上传
        if 'image' in request.files:
            file = request.files['image']
            if file.filename == '':
                return jsonify({'error': '未选择文件'}), 400
            
            # 保存临时文件
            import tempfile
            with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp_file:
                tmp_path = tmp_file.name
                file.save(tmp_path)
            
            try:
                # 执行OCR识别
                result = ocr_engine.recognize_from_file(tmp_path)
                return jsonify(result)
            finally:
                # 清理临时文件
                if os.path.exists(tmp_path):
                    os.unlink(tmp_path)
        
        # 检查是否有base64图片数据
        elif request.json and 'image_base64' in request.json:
            import base64
            image_base64 = request.json['image_base64']
            
            # 解码base64数据
            try:
                image_bytes = base64.b64decode(image_base64)
                result = ocr_engine.recognize_from_bytes(image_bytes)
                return jsonify(result)
            except Exception as e:
                return jsonify({'error': f'base64解码失败: {str(e)}'}), 400
        
        else:
            return jsonify({'error': '请上传图片文件或提供base64编码的图片数据'}), 400
            
    except Exception as e:
        import logging
        logging.error(f"OCR识别错误: {str(e)}")
        return jsonify({'error': f'识别失败: {str(e)}'}), 500

@app.route('/api/ocr-languages', methods=['GET'])
def ocr_languages():
    """获取OCR支持的语言列表"""
    return jsonify({
        'languages': ocr_engine.get_supported_languages()
    })

@app.route('/api/generate-image', methods=['POST'])
def generate_image():
    """文本生成图像接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        prompt = data.get('prompt', '').strip()
        size = data.get('size', '512x512')
        num_images = data.get('num_images', 1)
        style = data.get('style', 'photographic')
        
        if not prompt:
            return jsonify({"error": "请输入文本描述"}), 400
        
        # 调用文本生图算法
        result = image_generator.generate_image(prompt, size, num_images, style)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify({"error": result['error']}), 400
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/generate-image/sizes', methods=['GET'])
def get_image_sizes():
    """获取支持的图像尺寸列表"""
    try:
        sizes = image_generator.get_available_sizes()
        return jsonify({
            "sizes": sizes,
            "count": len(sizes)
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/generate-image/styles', methods=['GET'])
def get_image_styles():
    """获取支持的图像风格列表"""
    try:
        styles = image_generator.get_available_styles()
        return jsonify({
            "styles": styles,
            "count": len(styles)
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/translate', methods=['POST'])
def translate_text():
    """文本翻译接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        text = data.get('text', '').strip()
        source_lang = data.get('source_lang', 'auto')
        target_lang = data.get('target_lang', 'zh')
        
        if not text:
            return jsonify({"error": "请输入要翻译的文本"}), 400
        
        # 调用翻译算法
        result = translator_engine.translate_text(text, source_lang, target_lang)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify({"error": result['error']}), 400
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/translate/languages', methods=['GET'])
def get_translate_languages():
    """获取翻译支持的语言列表"""
    try:
        languages = translator_engine.get_supported_languages()
        return jsonify({
            "languages": languages,
            "count": len(languages)
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/translate/translators', methods=['GET'])
def get_translators():
    """获取支持的翻译服务"""
    try:
        translators = translator_engine.get_supported_translators()
        return jsonify({
            "translators": translators,
            "count": len(translators)
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/text-generation', methods=['POST'])
def text_generation():
    """文本生成接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        prompt = data.get('prompt', '').strip()
        max_length = data.get('max_length', 200)
        min_length = data.get('min_length', 50)
        temperature = data.get('temperature', 0.7)
        top_p = data.get('top_p', 0.9)
        system_prompt = data.get('system_prompt', None)
        
        if not prompt:
            return jsonify({"error": "请输入提示文本"}), 400
        
        # 调用文本生成算法
        result = generate_text_api(
            prompt=prompt,
            max_length=max_length,
            min_length=min_length,
            temperature=temperature,
            system_prompt=system_prompt
        )
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify({"error": result['error']}), 400
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/text-to-video', methods=['POST'])
def api_text_to_video():
    """文字转视频接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        text_content = data.get('text', '').strip()
        style = data.get('style', 'animated')
        duration = data.get('duration', 10)
        
        if not text_content:
            return jsonify({"error": "文本内容不能为空"}), 400
        
        # 调用文字转视频算法
        result_path = text_to_video(text_content, style, duration)
        
        # 检查文件是否存在
        if not os.path.exists(result_path):
            return jsonify({"error": "视频生成失败"}), 500
        
        # 返回文件路径
        return jsonify({
            "success": True,
            "video_path": result_path,
            "filename": os.path.basename(result_path)
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/split-video', methods=['POST'])
def api_split_video():
    """视频分割接口"""
    try:
        # 检查是否有文件上传
        if 'video' not in request.files:
            return jsonify({"error": "未找到视频文件"}), 400
        
        video_file = request.files['video']
        if video_file.filename == '':
            return jsonify({"error": "未选择视频文件"}), 400
        
        # 获取表单数据
        split_type = request.form.get('split_type', 'time')
        duration = int(request.form.get('duration', 10))
        
        # 保存上传的文件
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        upload_dir = os.path.join(project_root, 'uploads')
        os.makedirs(upload_dir, exist_ok=True)
        
        filename = secure_filename(video_file.filename)
        video_path = os.path.join(upload_dir, filename)
        video_file.save(video_path)
        
        # 调用视频分割算法
        result_paths = split_video(video_path, split_type, duration)
        
        # 清理上传的临时文件
        os.remove(video_path)
        
        return jsonify({
            "success": True,
            "video_paths": result_paths,
            "count": len(result_paths)
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/add-text', methods=['POST'])
def api_add_text_to_video():
    """为视频添加文字接口"""
    try:
        # 检查是否有文件上传
        if 'video' not in request.files:
            return jsonify({"error": "未找到视频文件"}), 400
        
        video_file = request.files['video']
        if video_file.filename == '':
            return jsonify({"error": "未选择视频文件"}), 400
        
        # 获取表单数据
        text_content = request.form.get('text', '').strip()
        font_size = int(request.form.get('font_size', 24))
        text_color = request.form.get('text_color', '#ffffff')
        position = request.form.get('position', 'center')
        
        if not text_content:
            return jsonify({"error": "文字内容不能为空"}), 400
        
        # 保存上传的文件
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        upload_dir = os.path.join(project_root, 'uploads')
        os.makedirs(upload_dir, exist_ok=True)
        
        filename = secure_filename(video_file.filename)
        video_path = os.path.join(upload_dir, filename)
        video_file.save(video_path)
        
        # 调用添加文字算法
        result_path = add_text_to_video(
            video_path, text_content, font_size, text_color, 
            position, 0, None
        )
        
        # 清理上传的临时文件
        os.remove(video_path)
        
        return jsonify({
            "success": True,
            "video_path": result_path,
            "filename": os.path.basename(result_path)
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/apply-transition', methods=['POST'])
def api_apply_transition():
    """视频转场效果接口"""
    try:
        # 获取上传的文件
        files = []
        file_keys = [key for key in request.files.keys() if key.startswith('video')]
        
        if len(file_keys) < 2:
            return jsonify({"error": "至少需要两个视频文件"}), 400
        
        # 保存所有上传的文件
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        upload_dir = os.path.join(project_root, 'uploads')
        os.makedirs(upload_dir, exist_ok=True)
        
        video_paths = []
        for key in file_keys:
            video_file = request.files[key]
            if video_file.filename == '':
                continue
                
            filename = secure_filename(video_file.filename)
            video_path = os.path.join(upload_dir, filename)
            video_file.save(video_path)
            video_paths.append(video_path)
        
        if len(video_paths) < 2:
            return jsonify({"error": "至少需要两个有效的视频文件"}), 400
        
        # 获取转场参数
        transition_category = request.form.get('transition_category', 'fade')
        duration = float(request.form.get('duration', 1))
        
        # 根据转场类型调用相应算法
        if transition_category == 'fade':
            fade_type = request.form.get('fade_type', 'cross')
            fade_curve = request.form.get('fade_curve', 'linear')
            result_path = apply_transition(
                video_paths, 'crossfade', 
                fade_type=fade_type, duration=duration
            )
        elif transition_category == 'slide':
            slide_direction = request.form.get('slide_direction', 'right')
            slide_type = request.form.get('slide_type', 'push')
            slide_speed = request.form.get('slide_speed', 'medium')
            result_path = apply_transition(
                video_paths, 'slide',
                direction=slide_direction, slide_type=slide_type, duration=duration
            )
        else:
            # 清理上传的文件
            for path in video_paths:
                os.remove(path)
            return jsonify({"error": "不支持的转场类型"}), 400
        
        # 清理上传的临时文件
        for path in video_paths:
            os.remove(path)
        
        return jsonify({
            "success": True,
            "video_path": result_path,
            "filename": os.path.basename(result_path)
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/download/<filename>', methods=['GET'])
def download_video(filename):
    """下载生成的视频文件"""
    try:
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        file_path = os.path.join(project_root, 'generated_videos', filename)
        
        if not os.path.exists(file_path):
            return jsonify({"error": "文件不存在"}), 404
        
        return send_file(file_path, as_attachment=True, download_name=filename)
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/preview/<filename>', methods=['GET'])
def preview_video(filename):
    """在线预览视频文件"""
    try:
        project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        file_path = os.path.join(project_root, 'generated_videos', filename)
        
        if not os.path.exists(file_path):
            return jsonify({"error": "文件不存在"}), 404
        
        return send_file(file_path, as_attachment=False, mimetype='video/mp4')
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/results', methods=['GET'])
def get_video_results():
    """获取所有生成的视频文件列表"""
    try:
        # 使用项目根目录的generated_videos文件夹
        project_root = os.path.dirname(os.path.abspath(__file__))
        results_dir = os.path.join(project_root, 'generated_videos')
        
        if not os.path.exists(results_dir):
            return jsonify({
                "success": True,
                "files": [],
                "message": "暂无生成的视频文件",
                "directory": results_dir
            })
        
        files = []
        for filename in os.listdir(results_dir):
            if filename.endswith('.mp4'):
                file_path = os.path.join(results_dir, filename)
                stat = os.stat(file_path)
                files.append({
                    "filename": filename,
                    "size": stat.st_size,
                    "created_time": stat.st_ctime
                })
        
        return jsonify({
            "success": True,
            "files": files
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/video/results/<filename>', methods=['GET'])
def get_video_info(filename):
    """获取单个视频文件的详细信息"""
    try:
        file_path = os.path.join('./algorithms/results', filename)
        
        if not os.path.exists(file_path):
            return jsonify({"error": "文件不存在"}), 404
        
        return jsonify({
            "success": True,
            "filename": filename,
            "path": os.path.abspath(file_path),
            "size": os.path.getsize(file_path),
            "created_time": os.path.getctime(file_path),
            "download_url": f"/api/video/download/{filename}",
            "preview_url": f"/api/video/preview/{filename}"
        })
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/emotion-analysis', methods=['POST'])
def emotion_analysis():
    """情感分析接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        text = data.get('text', '').strip()
        
        if not text:
            return jsonify({"error": "请输入要分析的文本"}), 400
        
        # 调用情感分析算法
        result = emotion_analyzer.analyze_emotion(text)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify({"error": result['error']}), 400
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/emotion-analysis/batch', methods=['POST'])
def emotion_analysis_batch():
    """批量情感分析接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        texts = data.get('texts', [])
        
        if not texts or not isinstance(texts, list):
            return jsonify({"error": "请提供文本列表"}), 400
        
        # 调用批量情感分析算法
        results = emotion_analyzer.analyze_batch(texts)
        
        return jsonify({
            "success": True,
            "results": results,
            "count": len(results)
        })
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/emotion-analysis/model-info', methods=['GET'])
def get_emotion_model_info():
    """获取情感分析模型信息"""
    try:
        model_info = emotion_analyzer.get_model_info()
        return jsonify(model_info)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/emotion-analysis/status', methods=['GET'])
def check_emotion_analysis_status():
    """检查情感分析服务状态"""
    try:
        status = emotion_analyzer.check_model_status()
        return jsonify(status)
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/watermark/remove-image', methods=['POST'])
def remove_watermark_image():
    """图片去水印接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        image_data = data.get('image', '')
        mask_coords = data.get('mask_coords', [])
        
        if not image_data:
            return jsonify({"error": "请提供图片数据"}), 400
        
        if not mask_coords or len(mask_coords) != 2:
            return jsonify({"error": "请提供有效的水印区域坐标"}), 400
        
        # 处理base64图片数据
        if image_data.startswith('data:image'):
            image_data = image_data.split(',')[1]
        
        import base64
        image_bytes = base64.b64decode(image_data)
        
        # 保存临时文件
        temp_input = f"temp_input_{int(time.time())}.jpg"
        with open(temp_input, 'wb') as f:
            f.write(image_bytes)
        
        try:
            # 调用去水印算法
            output_path = watermark_remover.remove_watermark_image(
                temp_input, 
                mask_coords
            )
            
            # 读取结果图片并转为base64
            with open(output_path, 'rb') as f:
                result_data = base64.b64encode(f.read()).decode('utf-8')
            
            # 清理临时文件
            os.remove(temp_input)
            os.remove(output_path)
            
            return jsonify({
                "success": True,
                "image": f"data:image/jpeg;base64,{result_data}",
                "format": "jpeg"
            })
            
        except Exception as e:
            # 清理临时文件
            if os.path.exists(temp_input):
                os.remove(temp_input)
            raise e
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/watermark/detect-regions', methods=['POST'])
def detect_watermark_regions():
    """自动检测水印区域接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        image_data = data.get('image', '')
        
        if not image_data:
            return jsonify({"error": "请提供图片数据"}), 400
        
        # 处理base64图片数据
        if image_data.startswith('data:image'):
            image_data = image_data.split(',')[1]
        
        import base64
        image_bytes = base64.b64decode(image_data)
        
        # 保存临时文件
        temp_input = f"temp_detect_{int(time.time())}.jpg"
        with open(temp_input, 'wb') as f:
            f.write(image_bytes)
        
        try:
            # 调用检测算法
            regions = watermark_remover.detect_watermark_region(temp_input)
            
            # 清理临时文件
            os.remove(temp_input)
            
            return jsonify({
                "success": True,
                "regions": regions,
                "count": len(regions)
            })
            
        except Exception as e:
            # 清理临时文件
            if os.path.exists(temp_input):
                os.remove(temp_input)
            raise e
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/watermark/remove-video', methods=['POST'])
def remove_watermark_video():
    """视频去水印接口"""
    try:
        if 'video' not in request.files:
            return jsonify({"error": "请上传视频文件"}), 400
        
        video = request.files['video']
        mask_coords = request.form.get('mask_coords')
        
        if not mask_coords:
            return jsonify({"error": "请提供水印区域坐标"}), 400
        
        try:
            mask_coords = eval(mask_coords)
        except:
            return jsonify({"error": "坐标格式错误"}), 400
        
        # 保存上传文件
        timestamp = int(time.time())
        input_filename = f"temp_video_{timestamp}.mp4"
        output_filename = f"cleaned_video_{timestamp}.mp4"
        
        video.save(input_filename)
        
        try:
            # 调用视频去水印算法
            output_path = watermark_remover.remove_watermark_video_simple(
                input_filename, 
                mask_coords
            )
            
            # 移动文件到结果目录
            results_dir = './generated_videos'
            os.makedirs(results_dir, exist_ok=True)
            final_path = os.path.join(results_dir, output_filename)
            shutil.move(output_path, final_path)
            
            # 清理临时文件
            os.remove(input_filename)
            
            return jsonify({
                "success": True,
                "video_path": final_path,
                "filename": output_filename,
                "download_url": f"/api/video/download/{output_filename}",
                "preview_url": f"/api/video/preview/{output_filename}"
            })
            
        except Exception as e:
            # 清理临时文件
            if os.path.exists(input_filename):
                os.remove(input_filename)
            raise e
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/text-summary', methods=['POST'])
def text_summary():
    """文本摘要接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        text = data.get('text', '').strip()
        max_length = data.get('max_length', 150)
        min_length = data.get('min_length', 30)
        
        if not text:
            return jsonify({"error": "请输入需要摘要的文本"}), 400
        
        if len(text) < 10:
            return jsonify({"error": "文本长度太短，无法生成有意义的摘要"}), 400
        
        # 调用文本摘要算法
        result = text_summarizer.summarize_text(text, max_length, min_length)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify({"error": result['error']}), 400
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/text-summary/batch', methods=['POST'])
def batch_text_summary():
    """批量文本摘要接口"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({"error": "无效的请求数据"}), 400
        
        texts = data.get('texts', [])
        max_length = data.get('max_length', 150)
        min_length = data.get('min_length', 30)
        
        if not texts or not isinstance(texts, list):
            return jsonify({"error": "请提供文本列表"}), 400
        
        if len(texts) > 10:  # 限制批量处理数量
            return jsonify({"error": "批量处理文本数量不能超过10个"}), 400
        
        # 调用批量文本摘要算法
        result = text_summarizer.batch_summarize(texts, max_length, min_length)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify({"error": result['error']}), 400
            
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/music-generation', methods=['POST'])
def music_generation():
    """使用Replicate API生成音乐"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'success': False,
                'error': '请提供请求数据'
            }), 400
        
        # 支持多种参数格式
        descriptions = data.get('descriptions', data.get('texts', data.get('prompts', [])))
        duration = min(max(float(data.get('duration', 5.0)), 1.0), 30.0)
        model_version = data.get('model_version', 'stereo-large')
        
        # 验证参数
        if not descriptions or not isinstance(descriptions, list):
            return jsonify({
                'success': False,
                'error': '请提供有效的音乐描述列表'
            }), 400
        
        if len(descriptions) > 8:
            return jsonify({
                'success': False,
                'error': '一次最多生成8个音乐'
            }), 400
        
        if model_version not in ['melody', 'medium', 'large', 'stereo-large']:
            model_version = 'stereo-large'
        
        # 清理旧文件
        music_generator.cleanup_old_files()
        
        # 使用Replicate API生成音乐
        result = music_generator.generate_music(
            descriptions=descriptions,
            duration=duration
        )
        
        if result['success']:
            # 构建访问URL
            base_url = f"{request.host_url.rstrip('/')}/static/musicgen_outputs"
            audio_urls = []
            
            for file_info in result['generated_files']:
                filename = file_info['filename']
                url = f"{base_url}/{filename}"
                audio_urls.append(url)
                file_info['url'] = url
            
            return jsonify({
                'success': True,
                'message': '音乐生成成功',
                'count': len(audio_urls),
                'audio_urls': audio_urls,
                'generated_files': result['generated_files']
            }), 200
        else:
            # 处理API错误
            error_msg = result['error']
            if 'replicate' in error_msg.lower():
                return jsonify({
                    'success': False,
                    'error': '云端服务暂时不可用，请稍后重试'
                }), 503
            else:
                return jsonify({
                    'success': False,
                    'error': error_msg
                }), 400
            
    except Exception as e:
        error_msg = str(e)
        if 'replicate' in error_msg.lower():
            return jsonify({
                'success': False,
                'error': '云端服务暂时不可用，请稍后重试'
            }), 503
        else:
            return jsonify({
                'success': False,
                'error': str(e)
            }), 500

@app.route('/api/music-generation/params', methods=['GET'])
def get_music_params():
    try:
        params = music_generator.get_supported_params()
        return jsonify({
            'success': True,
            **params
        }), 200
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@app.route('/api/music-generation/results', methods=['GET'])
def get_music_results():
    """获取所有生成的音乐文件列表"""
    try:
        project_root = os.path.dirname(os.path.abspath(__file__))
        results_dir = os.path.join(project_root, 'static', 'musicgen_outputs')
        
        if not os.path.exists(results_dir):
            return jsonify({
                "success": True,
                "files": [],
                "message": "暂无生成的音乐文件"
            })
        
        files = []
        for filename in os.listdir(results_dir):
            if filename.endswith(('.mp3', '.wav')):
                file_path = os.path.join(results_dir, filename)
                stat = os.stat(file_path)
                files.append({
                    "filename": filename,
                    "size": stat.st_size,
                    "created_time": stat.st_ctime,
                    "path": f"/static/musicgen_outputs/{filename}"
                })
        
        # 按创建时间排序，最新的在前
        files.sort(key=lambda x: x['created_time'], reverse=True)
        
        return jsonify({
            "success": True,
            "files": files,
            "count": len(files)
        })
        
    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500

@app.route('/api/music-generation/preview/<filename>', methods=['GET'])
def preview_music(filename):
    """在线预览音乐文件"""
    try:
        project_root = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(project_root, 'static', 'musicgen_outputs', filename)
        
        if not os.path.exists(file_path):
            return jsonify({"error": "文件不存在"}), 404
        
        return send_file(file_path, as_attachment=False, mimetype='audio/mpeg')
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/music-generation/download/<filename>', methods=['GET'])
def download_music(filename):
    """下载音乐文件"""
    try:
        project_root = os.path.dirname(os.path.abspath(__file__))
        file_path = os.path.join(project_root, 'static', 'musicgen_outputs', filename)
        
        if not os.path.exists(file_path):
            return jsonify({"error": "文件不存在"}), 404
        
        return send_file(file_path, as_attachment=True, download_name=filename)
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

def graceful_shutdown(signum, frame):
    print('\n🔄 正在优雅关闭服务...')
    time.sleep(2)
    print('✅ 服务已安全关闭')
    sys.exit(0)

# 注册信号处理
signal.signal(signal.SIGINT, graceful_shutdown)
signal.signal(signal.SIGTERM, graceful_shutdown)

if __name__ == '__main__':
    try:
        print("正在启动AI服务...")
        print("服务地址: http://localhost:5000")
        print("可用接口:")
        print(" - 语音合成: /api/voice-generation")
        print(" - OCR识别: /api/ocr-recognition") 
        print(" - 文本生图: /api/generate-image")
        print(" - 文本翻译: /api/translate")
        print(" - 视频编辑:")
        print("  * 文字转视频: /api/video/text-to-video")
        print("  * 视频分割: /api/video/split-video")
        print("  * 添加文字: /api/video/add-text")
        print("  * 转场效果: /api/video/apply-transition")
        print("  * 查看所有文件: /api/video/results")
        print("  * 查看单个文件: /api/video/results/<filename>")
        print("  * 下载视频: /api/video/download/<filename>")
        print(" - 文本生成: /api/text-generation")
        print(" - 情感分析: /api/emotion-analysis")
        print(" - 去水印功能:")
        print("  * 图片去水印: /api/watermark/remove-image")
        print("  * 视频去水印: /api/watermark/remove-video")
        print("  * 自动检测水印: /api/watermark/detect-regions")
        print(" - 文本摘要: /api/text-summary")
        print(" - 音乐生成: /api/music-generation")
        app.run(debug=True, host='0.0.0.0', port=5000, threaded=True)
    except KeyboardInterrupt:
        print('\n✅ 服务已停止')
    except Exception as e:
        print(f'❌ 启动错误: {e}')
